package com.weavernorth.fadada.util;

import com.alibaba.fastjson.JSONObject;
import com.weavernorth.util.MyCrypUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.*;

/**
 * @Author: bruseewang
 * @Package: com.weavernorth.fadada.util
 * @date: 2021/8/31 16:42
 * @description:
 */
public class fadadaUtil {
    public static final String appkey = "pIaubvnm08gxqXhwlyeofcKr";
    public static final String api_url_prefix = "https://local-demo-public.fadada.com/api-op19x";
    public static final String appId = "100000";
    public static final String signType = "SHA256";
    public static String timestamp = "";
    public static String biz_content = "";

    public static HashMap<String, Object> getParams(String timestamp, String sign, String bizContent) {
        HashMap<String, Object> params = new HashMap<>();
        params.put("appId", appId);
        params.put("signType", signType);
        params.put("sign", sign);
        params.put("timestamp", timestamp);
        params.put("bizContent", bizContent);
        return params;
    }

    /***
     * 账户注册
     * @return
     */
    public static String zhzc(String type, String account, String companyName) {
        String biz_content = null;
        LinkedHashMap<String, String> mp_content = new LinkedHashMap<>();
        mp_content.put("type", type);//注册类型：1：个人;2:企业
        mp_content.put("account", account);/*即账号。无门户，个人账号自定义；有门户，个人需要手机号or邮箱*/
        mp_content.put("adminAccountId", "");//企业管理员客户编号
        mp_content.put("companyName", companyName);//企业名称
        String str_json_content = JSONObject.toJSONString(mp_content);
//        System.out.println("json字符串："+str_json_content);
        try {
            //对json字符串进行特殊字符加密
            String content_encode = URLEncoder.encode(str_json_content, "UTF-8");
//            biz_content = Base64.getEncoder().encodeToString((content_encode).getBytes());
            biz_content = MyCrypUtils.Base64Encode((content_encode).getBytes());
            if (biz_content.equals("JTdCJTIydHlwZSUyMiUzQSUyMjIlMjIlMkMlMjJhY2NvdW50JTIyJTNBJTIyMTc2MDE5MTk5ODIlMjIlMkMlMjJhZG1pbkFjY291bnRJZCUyMiUzQSUyMiUyMiUyQyUyMmNvbXBhbnlOYW1lJTIyJTNBJTIyZXJkb3MlMjIlN0Q=")) {
                System.out.println("base64加密一致");
            } else {
                System.out.println("base64加密一致");
                System.out.println("加密后参数：" + biz_content);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            return biz_content;
        }
    }

    /***
     * 模糊查询客户编号
     * @return
     */
    public static String queryCustomer(String companyName) {
        String biz_content = null;
        LinkedHashMap<String, String> mp_content = new LinkedHashMap<>();
        mp_content.put("name", companyName);//企业名称
        String str_json_content = JSONObject.toJSONString(mp_content);
        System.out.println(str_json_content);
        try {
            //对json字符串进行特殊字符加密
            String content_encode = URLEncoder.encode(str_json_content, "UTF-8");
            biz_content = MyCrypUtils.Base64Encode((content_encode).getBytes());
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            return biz_content;
        }
    }

    /***
     * 合同生成-文件上传
     * @param docType
     * @param uploadType
     * @return
     */
    public static String uploadFile(String docType, String uploadType) {
        String biz_content = null;
        LinkedHashMap<String, String> mp_content = new LinkedHashMap<>();
        mp_content.put("docType", docType);//文件后缀
        mp_content.put("uploadType", uploadType); /**1-文件，2-图片*/
        String str_json_content = JSONObject.toJSONString(mp_content);
        try {
            //对json字符串进行特殊字符加密
            String content_encode = URLEncoder.encode(str_json_content, "UTF-8");
            biz_content = MyCrypUtils.Base64Encode((content_encode).getBytes());
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            return biz_content;
        }
    }

    /***
     * 模板管理-创建合同模板
     * @param tempNo 模板编号
     * @param personCustomerId 个人归属者客户编号，后面的版本已转到生成合同时
     * @param tempTitle 模板标题
     * @param tempPath 模板路径
     * @return
     */
    public static String cjhtmb(String tempNo, String personCustomerId, String tempTitle, String tempPath) {
        String biz_content = null;
        JSONObject json_content = new JSONObject();
        json_content.put("tempNo", tempNo);//模板编号
        json_content.put("personCustomerId", personCustomerId);//个人归属者客户编号，后面的版本已转到生成合同时
        json_content.put("companyCustomerId", "");//企业归属者客户编号，后面的版本已转到生成合同时
        json_content.put("tempTitle", tempTitle);//模板标题
        json_content.put("tempPath", tempPath);//模板路径
        json_content.put("tempExtension", ".pdf");//扩展名
        String str_json_content = json_content.toJSONString();
        try {
            //对json字符串进行特殊字符加密
            String content_encode = URLEncoder.encode(str_json_content, "UTF-8");
            biz_content = MyCrypUtils.Base64Encode(content_encode.getBytes());
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            System.out.println("加密后参数：" + biz_content);
            return biz_content;
        }
    }

    /***
     * 合同生成-模板填充生成合同
     * @param tempNo 模板编号
     * @param docTitle 合同标题
     * @param docNo 合同编号
     * @param parameterMap 模板填充内容，键值对形式，value支持填充图片，值格式需匹配正则表达式
     * @param personCustomerId 个人归属者客户编号
     * @return
     */
    public static String generate(String tempNo, String docTitle, String docNo, JSONObject parameterMap, String personCustomerId) {
        String biz_content = null;
        JSONObject json_content = new JSONObject();
        json_content.put("tempNo", tempNo);//模板编号
        json_content.put("docTitle", docTitle);//合同标题
        json_content.put("docNo", docNo);//合同编号
        json_content.put("fontSize", "");//模板填充字体大小
        json_content.put("fontType", "4");//模板填充字体类型，0-宋体；1-仿宋；2-黑体；3-楷体；4-微软雅黑，默认0
        json_content.put("parameterMap", JSONObject.toJSONString(parameterMap));//模板填充内容，键值对形式，value支持填充图片，值格式需匹配正则表达式
        json_content.put("personCustomerId", personCustomerId);//个人归属者客户编号
        json_content.put("companyCustomerId", "");//企业归属者客户编号
        String str_json_content = json_content.toJSONString();
        try {
            //对json字符串进行特殊字符加密
            String content_encode = URLEncoder.encode(str_json_content, "UTF-8");
            biz_content = MyCrypUtils.Base64Encode(content_encode.getBytes());
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            System.out.println("加密后参数：" + biz_content);
            return biz_content;
        }
    }

    /***
     * 调用法大大接口
     * @return
     */
    public static String sedDataTofdd(String url, Map<String, Object> params) {
        String api_url = api_url_prefix + url;
        String str_result = null;
        try {
            str_result = sendPost(api_url, "application/json", params, "json");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return str_result;

    }

    /***
     * 调用法大大接口
     * @return
     */
    public static String sedDataTofdd(String url, Map<String, Object> params, String contentType, File file) {
        String api_url = api_url_prefix + url;
        String str_result = null;
        try {
            str_result = sendPost_file(api_url, contentType, params, file);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return str_result;

    }

    public static String sendPost_file(String strUrl, String contentType, Map<String, Object> params, File file) throws IOException {
        String strBody = "";
        //创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();
        //创建post方式请求对象
        HttpPost httpPost = new HttpPost(strUrl);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);
        builder.addBinaryBody(
                "file",
                new FileInputStream(file),
                ContentType.APPLICATION_OCTET_STREAM,
                file.getName()
        );
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue().toString();
            builder.addTextBody(key, value);
        }
        HttpEntity multipart = builder.build();
        //设置参数到请求对象中
        httpPost.setEntity(multipart);
        //设置header信息
        //指定报文头【Content-type】、【User-Agent】
        //"application/json"
        httpPost.setHeader("Content-type", contentType);
        httpPost.setHeader("Connection", "keep-alive");
        httpPost.setHeader("Accept", "*/*");

        try {
            //执行请求操作，并拿到结果（同步阻塞）
            CloseableHttpResponse response = client.execute(httpPost);
            //获取结果实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                //按指定编码转换结果实体为String类型
                strBody = EntityUtils.toString(entity, "utf-8");
            }
            EntityUtils.consume(entity);
            //释放链接
            response.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return strBody;
    }

    public static String sendPost(String strUrl, String contentType, Map<String, Object> params, String sType) throws IOException {
        String strBody = "";
        //创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();
        //创建post方式请求对象
        HttpPost httpPost = new HttpPost(strUrl);
        //请求参数：key-value
        if (!"json".equals(sType)) {
            List<NameValuePair> pairList = new ArrayList<NameValuePair>(params.size());
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                BasicNameValuePair pair = new BasicNameValuePair(entry.getKey().toString(), entry.getValue().toString());
                System.out.println(pair);
                pairList.add(pair);
            }
            //设置参数到请求对象中
            httpPost.setEntity(new UrlEncodedFormEntity(pairList, "UTF-8"));
        } else {
            //装填参数：json
            com.alibaba.fastjson.JSONObject object = new JSONObject();
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                object.put(entry.getKey().toString(), entry.getValue().toString());
            }
            StringEntity stringEntity = new StringEntity(object.toString(), "utf-8");
            httpPost.setEntity(stringEntity);
        }
        //设置header信息
        //指定报文头【Content-type】、【User-Agent】
        //"application/json"
        httpPost.setHeader("Content-type", contentType);
        httpPost.setHeader("Connection", "keep-alive");
        httpPost.setHeader("Accept", "*/*");

        try {
            //执行请求操作，并拿到结果（同步阻塞）
            CloseableHttpResponse response = client.execute(httpPost);
//          log.info("返回状态=="+response);
            //获取结果实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                //按指定编码转换结果实体为String类型
                strBody = EntityUtils.toString(entity, "utf-8");
            }
            EntityUtils.consume(entity);
            //释放链接
            response.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return strBody;
    }

    /***
     * 判断连接是否可用
     * @param urlString
     * @param timeOutMillSeconds
     */
    public static Boolean connectUrlWithTimeOut(String urlString, int timeOutMillSeconds) {
        long lo = System.currentTimeMillis();
        Boolean result=true;
        URL url;
        try {
            url = new URL(urlString);
            URLConnection co = url.openConnection();
            co.setConnectTimeout(timeOutMillSeconds);
            co.connect();
            result=true;
        } catch (Exception e1) {
            result=false;
            url = null;
        }finally {
            System.out.println("连接耗时："+(System.currentTimeMillis() - lo));
            return result;
        }

    }
}
